import { UseEvent } from './types';

/**
 * Event key codes
 */
export enum KeyCode {
    enter = 13,
    esc = 27,
    space = 32,
    leftArrow = 37,
    upArrow = 38,
    rightArrow = 39,
    downArrow = 40,
    tab = 9,
    shift = 16
}

/**
 * Event key names
 */
export enum KeyName {
    enter = 'Enter',
    esc = 'Escape',
    space = ' ',
    leftArrow = 'ArrowLeft',
    upArrow = 'ArrowUp',
    rightArrow = 'ArrowRight',
    downArrow = 'ArrowDown',
    tab = 'Tab',
    shift = 'Shift'
}

export function useEvent(): UseEvent {

    function getKeyCodeFromEvent(event: KeyboardEvent): number {
        const key: any = event.key || event.keyCode;

        if (key === KeyName.enter || key === KeyCode.enter) {
            return KeyCode.enter;
        }
        if (key === KeyName.esc || key === KeyCode.esc) {
            return KeyCode.esc;
        }
        if (key === KeyName.space || key === KeyCode.space) {
            return KeyCode.space;
        }
        if (key === KeyName.leftArrow || key === KeyCode.leftArrow) {
            return KeyCode.leftArrow;
        }
        if (key === KeyName.upArrow || key === KeyCode.upArrow) {
            return KeyCode.upArrow;
        }
        if (key === KeyName.rightArrow || key === KeyCode.rightArrow) {
            return KeyCode.rightArrow;
        }
        if (key === KeyName.downArrow || key === KeyCode.downArrow) {
            return KeyCode.downArrow;
        }
        if (key === KeyName.tab || key === KeyCode.tab) {
            return KeyCode.tab;
        }
        if (key === KeyName.shift || key === KeyCode.shift) {
            return KeyCode.shift;
        }
        return -1;
    }

    return { getKeyCodeFromEvent };
}
